package com.kh.pajx.sop.view.action;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kh.pajx.sop.base.ModelDrivenBaseAction;
import com.kh.pajx.sop.domain.BossEcinfo;
import com.kh.pajx.sop.domain.HsSchoolInfo;
import com.kh.pajx.sop.domain.HsSchoolRelation;
import com.kh.pajx.sop.domain.SysArea;
import com.kh.pajx.sop.domain.SysDepartment;
import com.kh.pajx.sop.domain.SysDictionary;
import com.kh.pajx.sop.domain.SysInsideUser;
import com.kh.pajx.sop.domain.SysOutsideUser;
import com.kh.pajx.sop.util.common.ChineseToEnglish;
import com.kh.pajx.sop.util.common.DwzAjaxResult;
import com.kh.pajx.sop.util.common.FormatDate;
import com.kh.pajx.sop.util.page.QueryHelper;
import com.kh.pajx.sop.util.page.QueryHelperForManyTable;
import com.opensymphony.xwork2.ActionContext;

/**
 * Action控制器标准模版
 * 
 * @author: azzcsimp
 * @Createdate: 2014年6月12日 下午4:45:43
 */

@Controller("schoolAction")
@Scope("prototype")
/**
 *查询学校列表 
 */
public class SchoolAction extends ModelDrivenBaseAction<HsSchoolInfo> {

	private HsSchoolInfo hsSchoolInfo;
	private HsSchoolRelation hsSchoolRelation;
	private String id;
	private Map scList = new HashMap<String, HashMap<String, Object>>();// 创建map,key:学校编号，value：与学校对应的各种关联关系，如销售人员，客服人员，移动客户经理等
	private List<SysArea> areaList;
	private List<SysDepartment> departmentList;
	private String deptId;// 部门编号
	private List<SysDictionary> marketingTypeFlagList;// 激励方式
	private List<SysDictionary> balanceTypeFlagList;// 结算方式
	private List<BossEcinfo> bossEcinfoList;// 集团客户列表
	private String flag;// 标识


	/**
	 * 获取学校列表
	 * */
	public String schoolList() {
		Map request = (Map) ActionContext.getContext().get("request");
		init();// 初始化数据，加载字典等
		QueryHelper query = new QueryHelper(HsSchoolInfo.class, "d");
		QueryHelperForManyTable queryMany = new QueryHelperForManyTable(
				HsSchoolInfo.class, "school");
		queryMany.addColumns();
		queryMany.addTable(HsSchoolRelation.class, "schoolRelation")//
				.addColumns(0, "sclId ", 1, "sclId");
		if (hsSchoolInfo != null) {// 添加查询条件
			if (StringUtils.isNotEmpty(hsSchoolInfo.getSclName())
					&& !"".equals(hsSchoolInfo.getSclName())) {
				queryMany.addCondition(0, "sclName like ?",
						"%" + hsSchoolInfo.getSclName() + "%");
			}
		}
		queryMany.addCondition(1, "relationStatusFlag=?", "1");
		if (hsSchoolInfo != null) {// 添加查询条件
			if (StringUtils.isNotEmpty(hsSchoolRelation.getBalanceTypeFlag())
					&& !"".equals(hsSchoolRelation.getBalanceTypeFlag())) {
				queryMany.addCondition(1, "balanceTypeFlag=?",
						hsSchoolRelation.getBalanceTypeFlag());
			}
			/*
			 * if(StringUtils.isNotEmpty(hsSchoolRelation.getSaleUserId())&&!"".
			 * equals(hsSchoolRelation.getSaleUserId())){
			 * queryMany.addCondition(
			 * 1,"saleUserId=?",hsSchoolRelation.getSaleUserId()); }
			 */
			if (StringUtils.isNotEmpty(hsSchoolInfo.getAreaCode())
					&& !"".equals(hsSchoolInfo.getAreaCode())) {
				queryMany.addCondition(0, "areaCode=?",
						hsSchoolInfo.getAreaCode());
			}
		}
		if (deptId != null) {// 添加查询条件，例：如果选择市场一部，则查询销售人员是市场一部的所有学校信息
			if (StringUtils.isNotEmpty(deptId) && !"".equals(deptId)) {
			/*	List<SysInsideUser> sdUserList = sysInsideUserService
						.getUserByDeptNo(deptId);*/
				// TODO: 此处需要修改 deptId 为DeptCode   --azzcsimp 2014-07-23
				List<SysInsideUser> sdUserList = sysInsideUserService.getUserByDeptCode(deptId);
				String str = "(";// 用于拼接查到的人员信息id
				if (sdUserList.size() > 0) {// 如果该部门下人员为空的话则不添加条件
					for (int i = 0; i < sdUserList.size(); i++) {
						str += "'" + sdUserList.get(i).getIsuId() + "'";
						if (i != sdUserList.size() - 1) {
							str += ",";
						}
					}
					str += ")";

				} else {// 如果该部门下没有人
					str += "'')";
				}
				queryMany.addCondition(1, "saleUserId in " + str, null);
			}

		}
		queryMany.preparePageBean(schoolService, pageNum, numPerPage);
		List<HsSchoolInfo> recordList = (List<HsSchoolInfo>) request
				.get("recordList");
		for (HsSchoolInfo sc : recordList) {
			Map relationMap = new HashMap<String, Object>();// 创建map,用于存放与学校的关联关系
			HsSchoolRelation schoolrelation = schoolService
					.getSchoolRelationBySclId(sc.getSclId());
			SysInsideUser saler = schoolService.getUserBySclId(schoolrelation
					.getSaleUserId());// 与学校关联的销售人员
			SysInsideUser csUser = schoolService.getUserBySclId(schoolrelation
					.getCsUserId());// 与学校关联的客服人员
			BossEcinfo bossEcinfo = schoolService.getEcByEcId(schoolrelation
					.getEcId());
			/*SysOutsideUser mobManager = schoolService
					.getOutUserById(schoolrelation.getMobManagerId());// 移动客户经理
*/			
			SysOutsideUser mobManager = sysOutsideUserService.getById(schoolrelation.getMobManagerId());
			// OutsideUser
			// ec=schoolService.getOutUserById(schoolrelation.getEcId());//集团客户
			//SysArea area = schoolService.getAreaByCode(sc.getAreaCode());// 学校地区
			relationMap.put("relation", schoolrelation);
			relationMap.put("sale", saler);// 将学校对应的销售人员放入关系map
			relationMap.put("csUser", csUser);// 将学校对应的客服人员放入关系map
			relationMap.put("mobManager", mobManager);// 移动客户经理
			relationMap.put("ec", bossEcinfo);// 集团客户
			//relationMap.put("area", area);// 将地区放入学校关系map
			scList.put(sc.getSclId(), relationMap);// 将学校对应的关联关系全部放入map中
		}
		/*
		 * String str=
		 * "SELECT school FROM HsSchoolInfo school ,HsSchoolRelation schoolRelation where school.sclId=schoolRelation.sclId  and schoolRelation.relationStatusFlag='1'"
		 * ; schoolService.findByHql(str);
		 */
		return "school_list";
	}

	/**
	 * 跳转到编辑学校页面
	 */
	public String editSchoolUi() {
		Map request = (Map) ActionContext.getContext().get("request");
		init();// 初始化信息
		String id = (String) request.get("id");
		hsSchoolInfo = schoolService.getSchoolById(id);// 根据学校id查询学校信息
		hsSchoolRelation = schoolService.getSchoolRelationBySclId(hsSchoolInfo
				.getSclId());// 根据学校编号查询起作用的学校信息，即关联关系标示为1的。0：废弃,1:启用
	/*	SysOutsideUser sclManager = schoolService.getOutUserById(hsSchoolRelation
				.getSclManagerId());// 根据学校关系中的管理员id查询管理员
*/		
		SysOutsideUser sclManager = sysOutsideUserService.getById(hsSchoolRelation.getSclManagerId());
		
		SysInsideUser sale = schoolService.getUserBySclId(hsSchoolRelation
				.getSaleUserId());// 根据学校关系中的销售人员id查询销售人员
		/*SysOutsideUser mobManager = schoolService.getOutUserById(hsSchoolRelation
				.getMobManagerId());// 查询移动客户经理
*/		
		SysOutsideUser mobManager = sysOutsideUserService.getById(hsSchoolRelation.getMobManagerId());
		request.put("sclManager", sclManager);
		request.put("sale", sale);
		request.put("mobManager", mobManager);
		flag = (String) request.get("flag");
		if ("1".equals(flag) || "2".equals(flag)) {// 如果是审核或添加人修改
			return "school_update";
		}
		return "school_edit";
	}

	/**
	 * 领导修改学校操作，修改学校信息，新添一条学校关系
	 * 
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	public void updateSchool() throws IllegalAccessException,
			InvocationTargetException {
		Map request = (Map) ActionContext.getContext().get("request");
		String sclid = hsSchoolInfo.getSclId();
		String message = "保存失败";// 定义一个变量接收提示信息
		HsSchoolRelation oldSchoolRelation = schoolService
				.getSchoolRelationBySclId(hsSchoolInfo.getSclId());// 原学校关系
		HsSchoolRelation temp = new HsSchoolRelation();
		BeanUtils.copyProperties(temp, oldSchoolRelation);
		temp.setCardIssusrFlag(hsSchoolRelation.getCardIssusrFlag());// 发卡方
		temp.setCardTypeFlag(hsSchoolRelation.getCardTypeFlag());// 射频卡
		temp.setCreateTime(FormatDate.dateTimeDetail());
		temp.setBalanceTypeFlag(hsSchoolRelation.getBalanceTypeFlag());
		temp.setMarketingTypeFlag(hsSchoolRelation.getMarketingTypeFlag());
		temp.setRelationStatusFlag("1");
		oldSchoolRelation.setRelationStatusFlag("0");
		if (hsSchoolRelation.getMarketingTypeFlag().equals("3")) {
			//temp.setMarketingContent(hsSchoolRelation.getMarketingContent());
		} else {
			//temp.setMarketingContent("");
		}
		hsSchoolInfo.setCheckStatusFlag("1");
		String url = "schoolAction!editSchoolUi.action?id=" + sclid;
		String returnStr = "300";// 返回相应信息

		try {
			if (schoolService.updateSchoolInfo(hsSchoolInfo, temp)) {// 执行保存操作，实际上保存学校基本信息且新增一条学校关系信息
				message = "保存成功";
				url = "schoolAction!schoolList.action";
				returnStr = "200";
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			if (StringUtils.isEmpty(temp.getBalanceTypeFlag())) {
				message = "请选择结算方式";
			}
			if (StringUtils.isEmpty(temp.getMarketingTypeFlag())) {
				message = "请选择激励方式";
			}
			e.printStackTrace();
		} finally {
			// request.put("url", url);
			// request.put("message", message);
		}
		DwzAjaxResult result = new DwzAjaxResult();
		result.setStatusCode(returnStr);
		result.setMessage(message);
		result.setCallbackType("closeCurrent");
		result.setNavTabId("schoollist");
		DwzAjaxResult.josnMessage(result);
	}

	/**
	 * 添加人修改学校关系，领导审核，区别：添加人修改学校关系仅仅修改学校信息和学校关系信息，领导审核还修改学校状态为已审核
	 * 
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	public void update() throws IllegalAccessException,
			InvocationTargetException {
		Map request = (Map) ActionContext.getContext().get("request");
		flag = (String) request.get("flag");
		String message = "保存失败";// 定义一个变量接收提示信息
		String sclid = hsSchoolInfo.getSclId();
		String url = "schoolAction!editSchoolUi.action?id=" + sclid;
		String returnStr = "300";// 返回相应信息
		HsSchoolRelation oldSchoolRelation = schoolService
				.getSchoolRelationBySclId(hsSchoolInfo.getSclId());// 原学校关系
		HsSchoolRelation temp = new HsSchoolRelation();
		// BeanUtils.copyProperties(temp, oldSchoolRelation);
		oldSchoolRelation.setCardIssusrFlag(hsSchoolRelation
				.getCardIssusrFlag());// 发卡方
		oldSchoolRelation.setCardTypeFlag(hsSchoolRelation.getCardTypeFlag());// 射频卡
		// oldSchoolRelation.setCreateDate(FormatDate.dateTimeDetail());
		oldSchoolRelation.setBalanceTypeFlag(hsSchoolRelation
				.getBalanceTypeFlag());
		oldSchoolRelation.setMarketingTypeFlag(hsSchoolRelation
				.getMarketingTypeFlag());
		if (hsSchoolRelation.getMarketingTypeFlag().equals("3")) {
			//temp.setMarketingContent(hsSchoolRelation.getMarketingContent());
		} else {
			//temp.setMarketingContent("");
		}
		if ("2".equals(flag)) {// 如果是领导审核，则需要改变学校的状态为已审核；
			hsSchoolInfo.setCheckStatusFlag("1");
		}
		try {
			if (schoolService.updateSchool(hsSchoolInfo, oldSchoolRelation)) {// 执行保存操作，实际上保存学校基本信息且新增一条学校关系信息
				message = "保存成功";
				url = "schoolAction!schoolList.action";
				returnStr = "200";
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// request.put("url", url);
			// request.put("message", message);
		}
		DwzAjaxResult result = new DwzAjaxResult();
		result.setStatusCode(returnStr);
		result.setMessage(message);
		result.setCallbackType("closeCurrent");
		result.setNavTabId("schoollist");
		DwzAjaxResult.josnMessage(result);

	}

	/**
	 * 跳转至添加学校信息页面
	 * 
	 * @return
	 * @throws Exception
	 * @author lipengfei 2014/6/25
	 */
	public String skipAddSchool() throws Exception {
		ActionContext context = ActionContext.getContext();
		List<SysArea> sysAreaList = sysAreaService.findAll();
		/*
		 * azzcsimp 2014-07-23
		 * List<SysOutsideUser> mobManagerList = outsideUserService
				.findOutSideUserByType("1");
		List<SysOutsideUser> sclManagerList = outsideUserService
				.findOutSideUserByType("0");
		List<SysInsideUser> saleUserList = insideUserService.findByCode("1010",
				"001002");
		List<SysInsideUser> csUserList = insideUserService.findByCode("1006",
				"001001");*/
		
		List<SysOutsideUser> mobManagerList = sysOutsideUserService.findUserListByType(1);
		
		List<SysOutsideUser> sclManagerList = sysOutsideUserService.findUserListByType(0);
		
	/*	List<SysInsideUser> saleUserList = sysInsideUserService.getUserByDeptCode(deptCode);
		List<SysInsideUser> csUserList = insideUserService.findByCode("1006",
				"001001");*/
		
		
		
		
		List<SysDictionary> balanceTypeFlagList = sysDictionaryService
				.getDicListByTypeCode("20");
		List<SysDictionary> marketingTypeFlagList = sysDictionaryService
				.getDicListByTypeCode("21");
		context.put("sysAreaList", sysAreaList);
		context.put("mobManagerList", mobManagerList);
		context.put("sclManagerList", sclManagerList);
		//context.put("saleUserList", saleUserList);
		//context.put("csUserList", csUserList);
		context.put("balanceTypeFlagList", balanceTypeFlagList);
		context.put("marketingTypeFlagList", marketingTypeFlagList);
		return "skipAddSchool";
	}

	/**
	 * 添加学校信息.关系信息
	 * 
	 * @return
	 * @throws Exception
	 * @author lipengfei 2014/6/25
	 */
	public void addSchool() throws Exception {
		DwzAjaxResult result = new DwzAjaxResult();
		//学校代码自动获取lipengfei2014/7/9
		String sclNumber = "001";
		String area = hsSchoolInfo.getAreaCode().substring(0, 2);
		String Number = schoolService.getSclNumber(area);
		try {
			int num = Integer.parseInt(Number)+1;
			if (num <10&&num>0) {
				sclNumber = area + "00" + String.valueOf(num);
			} else if (num < 100) {
				sclNumber = area + "0" + String.valueOf(num);
			} else {
				sclNumber = area + String.valueOf(num);
			}
		} catch (Exception e) {
		}
		hsSchoolInfo.setSclNumber(sclNumber);
		String sclSpell = ChineseToEnglish
				.getPingYin(hsSchoolInfo.getSclName());
		hsSchoolInfo.setSclSpell(sclSpell);
		/*
		 * azzcsimp  2014-07-22修改
		 * // 添加创建人员信息lipengfei2014/7/8
		currentUser = (InsideUser) ServletActionContext.getRequest()
				.getSession().getAttribute("currentUser");
		hsSchoolRelation.setCreateOperId(currentUser.getIsuId());*/
		
		hsSchoolRelation.setCreateOperId(getCurrentUser().getUserId());
		
		
		hsSchoolInfo.setCheckStatusFlag("0");
		hsSchoolRelation.setRelationStatusFlag("1");
		try {
			boolean add = schoolService.addSchool(hsSchoolInfo,
					hsSchoolRelation);
			if (add) {
				result.setStatusCode("200");
				result.setMessage("操作成功!");
				result.setCallbackType("closeCurrent");
				result.setForwardUrl("");
				result.setConfirmMsg("");
				result.setNavTabId("schoollist");
				result.setRel("");
				DwzAjaxResult.josnMessage(result);
			}
		} catch (Exception e) {
			result.setMessage("保存失败");
			result.setStatusCode("300");
			DwzAjaxResult.josnMessage(result);
		}
	}

	/**
	 * 删除学校
	 */
	public String deleteSchool() {
		/*
		 * String hsSclId = school.getSclId(); HsSchoolInfo hsSchool =
		 * schoolService.getById(hsSclId); String saleUserId = school.get String
		 * ydUserId = school.getYdUserId(); String url =
		 * "schoolAction!editSchoolUi.action?id=" + hsSclId; String message =
		 * ""; try { initSchoolInfo(hsSchool, school);
		 * schoolService.modify(hsSchool); message = "保存成功!"; } catch (Exception
		 * e) { message = "保存失败!"; e.printStackTrace(); } school = new
		 * HsSchool(); request.setAttribute("message", message);
		 */
		String hsSclId = hsSchoolInfo.getSclId();
		return "alertmsg";
	}

	/**
	 * 显示绑定集团客户页面
	 * 
	 * @author xujiangtao
	 */
	public String addBossEcUi() {
		hsSchoolInfo = schoolService.getSchoolById(id);
		hsSchoolRelation = schoolService.getSchoolRelationBySclId(hsSchoolInfo
				.getSclId());
		bossEcinfoList = schoolService.findAllBossEcinfo();
		return "addBossUi";
	}

	/**
	 * 绑定集团客户
	 * 
	 * @author xujiangtao
	 */
	public void addBossEc() {
		String message = "绑定失败！";
		String returnStr = "300";// 返回相应信息
		hsSchoolRelation = schoolService.getSchoolRelationBySclId(hsSchoolInfo
				.getSclId());
		hsSchoolRelation.setEcId(id);
		if (schoolService.updateSchoolRelation(hsSchoolRelation)) {
			message = "绑定成功";
			returnStr = "200";
		}
		DwzAjaxResult result = new DwzAjaxResult();
		result.setStatusCode(returnStr);
		result.setMessage(message);
		result.setCloseDialog("addBossEc");
		result.setNavTabId("schoollist");
		DwzAjaxResult.josnMessage(result);

	}

	/**
	 * 初始化方法，将与学校有关联的信息查出
	 * 
	 * @author xujiangtao
	 */
	public void init() {
		areaList = schoolService.findAllArea();
		//
		//departmentList = departmentService.findChildrenByParentCode("002000");// 获取市场部所有部门
		balanceTypeFlagList = sysDictionaryService.getDicListByTypeCode("20");// 获取结算方式下的字典
		marketingTypeFlagList = sysDictionaryService.getDicListByTypeCode("21");// 获取激励方式的字典
	}

	// ===========================为变量添加get,set方法
	public List<SysDictionary> getMarketingTypeFlagList() {
		return marketingTypeFlagList;
	}

	public void setMarketingTypeFlagList(
			List<SysDictionary> marketingTypeFlagList) {
		this.marketingTypeFlagList = marketingTypeFlagList;
	}

	public List<SysDictionary> getBalanceTypeFlagList() {
		return balanceTypeFlagList;
	}

	public void setBalanceTypeFlagList(List<SysDictionary> balanceTypeFlagList) {
		this.balanceTypeFlagList = balanceTypeFlagList;
	}

	public String getDeptId() {
		return deptId;
	}

	public void setDeptId(String deptId) {
		this.deptId = deptId;
	}


	public List<SysArea> getAreaList() {
		return areaList;
	}

	public void setAreaList(List<SysArea> areaList) {
		this.areaList = areaList;
	}

	private List<SysInsideUser> saleList;

	public List<SysInsideUser> getSaleList() {
		return saleList;
	}

	public void setSaleList(List<SysInsideUser> saleList) {
		this.saleList = saleList;
	}

	public Map getScList() {
		return scList;
	}

	public void setScList(Map scList) {
		this.scList = scList;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public HsSchoolInfo getHsSchoolInfo() {
		return hsSchoolInfo;
	}

	public void setHsSchoolInfo(HsSchoolInfo hsSchoolInfo) {
		this.hsSchoolInfo = hsSchoolInfo;
	}

	public HsSchoolRelation getHsSchoolRelation() {
		return hsSchoolRelation;
	}

	public void setHsSchoolRelation(HsSchoolRelation hsSchoolRelation) {
		this.hsSchoolRelation = hsSchoolRelation;
	}

	public List<BossEcinfo> getBossEcinfoList() {
		return bossEcinfoList;
	}

	public void setBossEcinfoList(List<BossEcinfo> bossEcinfoList) {
		this.bossEcinfoList = bossEcinfoList;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public List<SysDepartment> getDepartmentList() {
		return departmentList;
	}

	public void setDepartmentList(List<SysDepartment> departmentList) {
		this.departmentList = departmentList;
	}
	
	

}
